package com.shi.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class HighLevelEsClientController {

    @RequestMapping("getDoc")
    public Object getDoc() throws IOException {
        // 创建一个 RestClient
        RestClient restClient = RestClient.builder(
                        new HttpHost("localhost", 9200, "http"))
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    // 设置认证信息（如果需要）
                    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                    //credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                })
                .build();

        // 创建一个 ElasticsearchTransport
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // 创建一个 ElasticsearchClient
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 获取文档
        GetResponse<Object> response = client.get(g -> g
                .index("test_index")
                .id("888"), Object.class);

        if (response.found()) {
            System.out.println(response.source());
            return response.source();
        } else {
            System.out.println("Document not found.");
            return null;
        }

        // 关闭 RestClient 和 ElasticsearchTransport
    }
}
